//
//  QJKaiDianVCTwo.m
//  QuanJieShopProject
//
//  Created by apple on 2018/2/27.
//  Copyright © 2018年 apple. All rights reserved.
//
#define Key_DistrictSelectProvince          @"DistrictSelectProvince"
#define Key_DistrictSelectProvinceCode      @"DistrictSelectProvinceCode"
#define Key_DistrictSelectProvinceSubCode   @"DistrictSelectProvinceSubCode"
#define Key_DistrictSelectProvinceSub       @"DistrictSelectProvinceSub"
#define Key_DistrictSelectCityCode          @"DistrictSelectCityCode"
#define Key_DistrictSelectCity              @"DistrictSelectCity"

#import "GPDateView.h"
#import "QJKaiDianVCTwo.h"
#import "QJKaiDianHeaderTwo.h"
#import "QJLocationInfoModel.h"
#import "QJKDVCThree.h"
//商家分类
#import "QJKDCategorySelectView.h"
#import "SOPopViewTool.h"
//地区选择
//#import "QJMineAddressSelectView.h"
#import "YFMapLocationVC.h"

@interface QJKaiDianVCTwo () <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UITableView *kdTableView;
@property (nonatomic, strong) QJKaiDianHeaderTwo *kdHeaderView;
@property (nonatomic, strong) QJKDCategorySelectView *categoryView;
//@property (nonatomic, strong) QJMineAddressSelectView *selectView;
@property (nonatomic, strong) KaiDianModel *kdModel;
@property (nonatomic, strong) NSString *companyStr;   //主体名称
@property (nonatomic, strong) NSString *linkStr;      //联系人姓名
@property (nonatomic, strong) NSString *mobileStr;    //电话号码
@property (nonatomic, strong) NSString *categoryStr;  //商家分类
@property (nonatomic, strong) NSString *shengStr;     //省
@property (nonatomic, strong) NSString *shiStr;       //市
@property (nonatomic, strong) NSString *quStr;        //区
@property (nonatomic, strong) NSString *addressStr;   //详细地址
@property (nonatomic, strong) NSString *longitudeStr; //经度
@property (nonatomic, strong) NSString *latitudeStr;  //纬度
@property (nonatomic, strong) NSString *legalStr;     //法人姓名
@property (nonatomic, strong) NSString *idcardOneStr; //身份证正面
@property (nonatomic, strong) NSString *idcardTwoStr; //身份证反面
@property (nonatomic, strong) NSString *idcardType;
@property (nonatomic, strong) UIImage *idcardImageOne;
@property (nonatomic, strong) UIImage *idcardImageTwo;
@end

@implementation QJKaiDianVCTwo

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupKaiDianVCAction];
}
- (void)setupKaiDianVCAction{
    self.title = @"开店";
    self.kdHeaderView = [[[NSBundle mainBundle]loadNibNamed:@"QJKaiDianHeaderTwo" owner:self options:nil]firstObject];
    self.kdHeaderView.frame = CGRectMake(0, 0, UISCREEN_WIDTH, 600);
    
    self.kdTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, UISCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.kdTableView];
    self.kdTableView.tableHeaderView = self.kdHeaderView;
    WEAKSELF
    self.kdHeaderView.headerBtnClickBlock = ^(NSInteger tag) {
        switch (tag) {
            case 300:
            {
                //商家分类
                [weakSelf categorySelectAction];
            }
                break;
            case 301:
            {
                //所在地区
                [weakSelf citySelectAction];
            }
                break;
            case 302:
            {
                //身份证正面
                [weakSelf imageUploadActionWithType:@"one"];
            }
                break;
            case 303:
            {
                //身份证反面
                [weakSelf imageUploadActionWithType:@"two"];
            }
                break;
            case 304:
            {
                //下一步
                [weakSelf nextBtnClickAction];
            }
                break;
            case 305: // 图片按钮
            {
                // 百度地图
                YFMapLocationVC *vc = [[YFMapLocationVC alloc] init];
                vc.locationAddressBlock = ^(QJLocationInfoModel *model) {
                    weakSelf.kdHeaderView.sixTF.text = [NSString stringWithoutNilFormart:model.name];
                    weakSelf.addressStr = [NSString stringWithoutNilFormart:model.name];
                    
                    weakSelf.kdHeaderView.sixTF.enabled = YES;
                    weakSelf.kdHeaderView.sixTF.userInteractionEnabled = YES;
                    
                    // 本来就是百度地图, 无需再转换了
                    weakSelf.longitudeStr = [NSString stringWithFormat:@"%.6f",model.coordinate.longitude];
                    weakSelf.latitudeStr = [NSString stringWithFormat:@"%.6f",model.coordinate.latitude];
                };
                KPushViewControllerAction(vc);
            }
                break;
            default:
                break;
        }
    };
}
#pragma mark -- 商家分类方法
- (void)categorySelectAction{
    WEAKSELF
//    [[SOPopViewTool sharedInstance] popView:self.categoryView animated:YES];
//    self.categoryView.categoryIDSelectBlock = ^(NearCategoryModel *model) {
//        [[SOPopViewTool sharedInstance]closeAnimated:YES];
//        weakSelf.kdHeaderView.fourTF.text = [NSString stringWithoutNilFormart:model.category_name];
//        weakSelf.categoryStr = [NSString stringWithoutNilFormart:model.id];
//    };
//    self.categoryView.cancelBtnClickBlock = ^{
//        [[SOPopViewTool sharedInstance]closeAnimated:YES];
//    };
}
#pragma mark -- 所在地区方法
- (void)citySelectAction{
    
    GPDateView * dateView = [[GPDateView alloc] initWithFrame:CGRectMake(0, UISCREEN_HEIGHT-250, UISCREEN_WIDTH, 250) Data:nil];
    
    [dateView showPickerView];
    
    dateView.ActionDistrictViewSelectBlock = ^(NSString *desStr,NSDictionary *selectDistrictDict){
        
        NSString *provine = [selectDistrictDict objectForKey:Key_DistrictSelectProvince];
        NSString *city = [selectDistrictDict objectForKey:Key_DistrictSelectCity];
        NSString *district = [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub];
        self.kdHeaderView.fiveTF.text = [NSString stringWithFormat:@"%@-%@-%@",provine,city,district];
        
    };
//    WEAKSELF
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
//    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
//    [self.view addSubview:view];
    
//    QJMineAddressSelectView *selectView = [[[NSBundle mainBundle]loadNibNamed:@"QJMineAddressSelectView" owner:self options:nil]firstObject];
//    selectView.frame = CGRectMake(0, UISCREEN_HEIGHT, UISCREEN_WIDTH, 256);
//    self.selectView = selectView;
//    [selectView setupUIAction];
//    [self.view addSubview:self.selectView];
//    [UIView animateWithDuration:0.5 animations:^{
//        selectView.frame = CGRectMake(0, UISCREEN_HEIGHT - 256, UISCREEN_WIDTH, 256);
//    } completion:^(BOOL finished) {
//    }];
//
//    selectView.selectResultBlock = ^(NSString *result) {
//        if (result.length > 0) {
//            weakSelf.kdHeaderView.fiveTF.text = result;
//        }
//        [view removeFromSuperview];
//        [UIView animateWithDuration:0.5 animations:^{
//            weakSelf.selectView.frame = CGRectMake(0, UISCREEN_HEIGHT, UISCREEN_WIDTH, 256);
//        } completion:^(BOOL finished) {
//            [weakSelf.selectView removeFromSuperview];
//        }];
//    };
}
#pragma mark -- 图片上传方法
- (void)imageUploadActionWithType:(NSString *)typeStr{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self gotoIamgePickerWith: UIImagePickerControllerSourceTypeCamera];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self gotoIamgePickerWith: UIImagePickerControllerSourceTypePhotoLibrary];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cameraAction];
    [alert addAction:photoAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
    self.idcardType = typeStr;
}
#pragma mark -- 选择图片来源
- (void)gotoIamgePickerWith:(NSUInteger)sourceType{
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [MBPHUD showAlertWithTitle:@"您没有对相机授权!"];
            return;
        }
        
    }else{
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [MBPHUD showAlertWithTitle:@"您没有对相册授权!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{
    }];
}
#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    
    [self dismissViewControllerAnimated:YES completion:nil];
//    NSData *data = UIImageJPEGRepresentation(image, 1);
    if ([self.idcardType isEqualToString:@"one"]) {
        //正面
        self.idcardImageOne = image;
        [self.kdHeaderView.oneBtn setImage:image forState:UIControlStateNormal];
    }else if ([self.idcardType isEqualToString:@"two"]){
        //反面
        self.idcardImageTwo = image;
        [self.kdHeaderView.twoBtn setImage:image forState:UIControlStateNormal];
    }
    
}

#pragma mark -- 照片上传参数
- (NSMutableDictionary *)uploadDict {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"shop" forKey:@"savepath"];
    [dict setObject:@"banner" forKey:@"pictitle"];
    [dict setObject:@"image" forKey:@"dir"];
    return dict;
}
#pragma mark -- 正面上传
- (void)uploadImageOneAction{
    
    [[HttpManager shareHttpManager] postImagefileWithUrl:kUploadImage parameter:[self uploadDict] withImageFile:self.idcardImageOne hiddenHUD:YES HUDTitle:@"正在提交信息..." success:^(NSURLSessionDataTask *operetion, id response) {
        NSLog(@"正面 = response = %@", response);

        if (response) {
            self.kdModel.idCardUrl = response[@"url"];
            [self uploadImageTwoAction];
        }
    } failure:^(NSURLSessionDataTask *operetion, id response) {
//        [MBPHUD showAlertWithTitle:@"身份证正面照提交失败,请重新提交!"];
    }];
}
#pragma mark -- 反面上传
- (void)uploadImageTwoAction{
    [[HttpManager shareHttpManager] postImagefileWithUrl:kUploadImage parameter:[self uploadDict] withImageFile:self.idcardImageTwo hiddenHUD:YES HUDTitle:@"正在提交信息..." success:^(NSURLSessionDataTask *operetion, id response) {
        
        NSLog(@"反面 = response = %@", response);

        if (response) {
            self.kdModel.idCardUrl2 = response[@"url"];
            
            QJKDVCThree *VC = [[QJKDVCThree alloc]init];
            VC.kdModel = self.kdModel;
            
            [self.navigationController pushViewController:VC animated:YES];
        }
    } failure:^(NSURLSessionDataTask *operetion, id response) {
//        [MBPHUD showAlertWithTitle:@"身份证反面照提交失败,请重新提交!"];
    }];
}
#pragma mark -- 点击下一步的方法
- (void)nextBtnClickAction{
    //数据处理
    self.companyStr = [NSString stringWithFormat:@"%@",self.kdHeaderView.oneTF.text];
    self.linkStr = [NSString stringWithFormat:@"%@",self.kdHeaderView.twoTF.text];
    self.mobileStr = [NSString stringWithFormat:@"%@",self.kdHeaderView.threeTF.text];
    NSString *selectStr = [NSString stringWithFormat:@"%@",self.kdHeaderView.fiveTF.text];
    NSArray *arr = [selectStr componentsSeparatedByString:@"-"];
    if (arr.count == 3) {
        self.shengStr = [NSString stringWithFormat:@"%@",arr[0]];
        self.shiStr = [NSString stringWithFormat:@"%@",arr[1]];
        self.quStr = [NSString stringWithFormat:@"%@",arr[2]];
    }
    self.legalStr = [NSString stringWithFormat:@"%@",self.kdHeaderView.sevenTF.text];
    
    self.kdModel.companyName = self.companyStr;
    self.kdModel.linkName = self.linkStr;
    self.kdModel.tel = self.mobileStr;
    self.kdModel.categoryNearId = self.categoryStr;
    self.kdModel.provice = self.shengStr;
    self.kdModel.city = self.shiStr;
    self.kdModel.region = self.quStr;
    self.kdModel.detailAddress = self.addressStr;
    self.kdModel.longitude = self.longitudeStr;
    self.kdModel.latitude = self.latitudeStr;
    self.kdModel.legalPerson = self.legalStr;
    if (self.companyStr.length > 0 && self.linkStr.length > 0 && self.mobileStr.length > 0 && self.categoryStr.length > 0 && selectStr.length > 0 && self.addressStr.length > 0 && self.legalStr.length > 0 && self.idcardImageOne && self.idcardImageTwo) {
        [self uploadImageOneAction];
    }else{
        [MBPHUD showAlertWithTitle:@"请检查所需信息是否完整!"];
    }
    
    
}
#pragma mark -- 懒加载
- (QJKDCategorySelectView *)categoryView{
    if (!_categoryView) {
       _categoryView = [[[NSBundle mainBundle]loadNibNamed:@"QJKDCategorySelectView" owner:self options:nil] firstObject];
        _categoryView.frame = CGRectMake(0, 0, UISCREEN_WIDTH - 40, 300);
        [_categoryView setupSelectUIAction];
    }
    return _categoryView;
}
- (KaiDianModel *)kdModel{
    if (!_kdModel) {
        _kdModel = [[KaiDianModel alloc]init];
    }
    return _kdModel;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
